<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\Fields;
use think\Db;
use fast\Random;
use app\admin\library\Time;
use think\Request;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 *
 *
 * @icon fa fa-circle-o
 */
class Millionproject extends Backend
{

    /**
     * Millionproject模型对象
     * @var \app\admin\model\Millionproject
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->relationtTable = 'street';
        $this->model = new \app\admin\model\Millionproject;
        $this->assignconfig('isSuperAdmin',$this->auth->isSuperAdmin());
        $this->assign('isSuperAdmin',$this->auth->isSuperAdmin());
        if($this->auth->isSuperAdmin())
            $this->pre = '';
        else
            $this->pre = 'tmp_';
        $this->assign('pre',$this->pre);

        $this -> tmpFields = [
            'tmp_scope_business',
            'tmp_investment_name',
            'tmp_investment_type_id',
            'tmp_investment_type_name',
            'tmp_register_time',
            'tmp_investment_total',
            'tmp_registered_capital',
            'tmp_external_registered_capital',
            'tmp_actual_registered_capital',
            'tmp_industry_type_id',
            'tmp_industry_type_name',
            'tmp_floor_area',
            'tmp_street_id',
            'tmp_street_name',
            'tmp_progression',
            'tmp_is_buy_land',
            'tmp_handle_procedures'

        ];

        $this -> tmpFieldNames = [
            'tmp_scope_business' => '经营范围',
            'tmp_investment_name' => '投资方名称',
            'tmp_investment_type_id' => '投资方式',
            'tmp_investment_type_name' => '投资方式',
            'tmp_register_time' => '注册时间',
            'tmp_investment_total' => '总投资',
            'tmp_registered_capital' => '注册资本',
            'tmp_external_registered_capital' => '市外注册资本',
            'tmp_actual_registered_capital' => '实际利用内资',
            'tmp_industry_type_id' => '产业类型',
            'tmp_industry_type_name' => '产业类型',
            'tmp_floor_area' => '占地或租赁面积',
            'tmp_street_id' => '所在街道',
            'tmp_street_name' => '所在街道',
            'tmp_progression' => '进展情况',
            'tmp_is_buy_land' => '是否购地',
            'tmp_handle_procedures' => '土地、规划、发改、环评等手续办理情况'

        ];

        $this -> fieldNames = [
            'scope_business' => '经营范围',
            'investment_name' => '投资方名称',
            'investment_type_id' => '投资方式',
            'investment_type_name' => '投资方式',
            'register_time' => '注册时间',
            'investment_total' => '总投资',
            'registered_capital' => '注册资本',
            'external_registered_capital' => '市外注册资本',
            'actual_registered_capital' => '实际利用内资',
            'industry_type_id' => '产业类型',
            'industry_type_name' => '产业类型',
            'floor_area' => '占地或租赁面积',
            'street_id'=>'所在街道',
            'street_name' => '所在街道',
            'progression' => '进展情况',
            'is_buy_land' => '是否购地',
            'handle_procedures' => '土地、规划、发改、环评等手续办理情况'
        ];

        $investment_type= [
            "" => "请选择",
            "1" => "独资",
            "2" => "合作",
            "3" => "合资"
        ];
        $industry_type= [
            "" => "请选择",
            "1" => "独资",
            "2" => "合作",
            "3" => "合资"
        ];
        $this -> assign('investment_type',$investment_type);
        $this -> assign('industry_type',$industry_type);
        // pr(["" => "请选择"]+getSelectList('chargedep',['group_id'=>5]));
        $this -> assign('streets',["" => "请选择"]+getSelectList('chargedep',['group_id'=>5]));
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                // 非管理员需要经过审核
                $insertData = [];
                if(!$this -> auth -> isSuperAdmin()){
                    foreach ($params as $k => &$v) {
                        if($k == 'name') {
                            $insertData['name'] = $v;
                        }

                        $insertData['tmp_'.$k] = $v;
                        unset($params[$k]);
                    }
                    $insertData['status'] = 100;
                    $params = $insertData ?? $params;
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $id = $this -> model -> getLastInsID();
                    //写入接洽记录

                    //写入日志
                    $logData = [];
                    $row = $this -> model -> find($id);
                    foreach ($this -> tmpFieldNames as $k => $v) {
                        $k = $this -> auth -> isSuperAdmin() ? $this -> ltrim($k) : $k;
                        if(isset($row -> $k) && $row -> $k){
                            $logData[] = [
                                'millionproject_id' => $id,
                                'admin_id'  => $this -> auth -> id,
                                'field' => $k,
                                'field_name' => $v,
                                'new_value' => $row -> $k,
                                'status' => 300,
                                'info'  => '项目创建',
                                'create_time' => time(),
                                'update_time'   => time()
                            ];
                        }
                    }
                    Db::name('millionprojectlog') -> insertAll($logData);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        return $this->view->fetch();
    }

    public function edit($ids = NULL) {
        if(!$ids) $this -> error('请重试');
        $row = $this -> model -> find($ids);



        if($this -> request -> isPost()){
            $data = $this -> request -> post('row/a');
            $updateData = [];
            $logData = [];
            foreach ($data as $k => $v) {
                if(is_array($v)){
                    $data[$k] = implode(',',$v);
                }
                if(isset($row -> $k) && $row -> $k != $data[$k]){
                    if(is_int($row -> $k) && date("Y-m-d",$row -> $k) == $data[$k]) continue;
                    $key = $this -> auth -> isSuperAdmin() ? $k : 'tmp_'.$k;
                    $updateData[$key] = $data[$k];
                    $logData[] = [
                        'millionproject_id' => $row -> id,
                        'admin_id'  => $this -> auth -> id,
                        'field' => $k,
                        'field_name' => $this -> tmpFieldNames[$k] ?? ($this -> fieldNames[$k] ?? ''),
                        'ori_value' => $row -> $k,
                        'new_value' => $data[$k],
                        'status' => $this -> auth -> isSuperAdmin() ? 300 : 100,
                        'info'  => $this -> auth -> isSuperAdmin() ? '管理员修改' : '申请提交',
                        'create_time' => time(),
                        'update_time'   => time()
                    ];
                }
            }
            Db::name('millionprojectlog') -> insertAll($logData);
            if($updateData){
                $ret = $row -> save($updateData);
                $this -> success('成功');
            }else{
                $this -> error('无数据修改');
            }
        }
        $this -> assign('row',$row);
        return $this->view->fetch();
    }

    public function checkedit($ids = null){
        if(!$ids) $this -> error('请重试');
        $row = $this -> model -> find($ids);

        $chargeDepsArr = \app\admin\model\Chargedep::all();
        $chargeDeps = [];
        foreach ($chargeDepsArr as $dep){
            $chargeDeps[$dep -> id] = $dep -> name;
        }

        $this -> assign('row',$row);
        return $this -> fetch();
    }

    public function checkpass($ids = null){
        if(!$ids || !$this -> auth -> isSuperAdmin()) $this -> error('请刷新重试，或者您不是管理员');
        $rows = $this ->model -> whereIn('id',$ids) -> select();
        return $this -> check($rows,'pass');
    }

    public function checkreject($ids = null){
        if(!$ids || !$this -> auth -> isSuperAdmin()) $this -> error('请刷新重试，或者您不是管理员');
        $rows = $this ->model -> whereIn('id',$ids) -> select();
        if($this -> request -> isPost()){
            return $this -> check($rows,'reject');
        }
        $this -> assign('ids',$ids);
        return $this -> fetch();
    }

    /**
     * 一键通过所有
     */
    public function passall(){
        $rows = $this -> model -> where(['status' => 100]) -> select();
        if(!$rows){
            $this -> error('暂无需要审核的项目');
        }
        return $this -> check($rows,'pass');
    }

    private function check($rows = null, $action = null){
        if(!$rows || !$action) $this -> error('请刷新重试');


        $ret = true;
        foreach ($rows as $row){
            if('pass' == $action){
                foreach ($this->tmpFields as $tmpField) {
                    if($row -> $tmpField){
                        $field = $this -> ltrim($tmpField);
                        $row -> $field = $row -> $tmpField;
                        $row -> $tmpField = null;
                    }
                }
                $row -> status = 0; // 通过
                $row -> reject_reason = '';

                Db::name('millionprojectlog') -> where(['status' => 100,'millionproject_id' => $row -> id]) -> update(['status' => 300]);
            }else{
                $row -> reject_reason = $this -> request -> post('reject_reason');
                $row -> status = 200; // 驳回
                Db::name('millionprojectlog') -> where(['status' => 100,'millionproject_id' => $row -> id]) -> update(['status' => 200]);
            }
            $ret = $row -> save();
        }
        if($ret !== false){
            $this -> success('成功');
        }
    }

    private function ltrim($tmpField){
        if(substr($tmpField,0,4) == 'tmp_'){
            return substr($tmpField,4);
        }
    }


    public  function import() {

        if($this->request->isPost()){
            $file = $this->request->request('filepath');
            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
            $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

            $table = $this->model->getQuery()->getTable();
            $database = \think\Config::get('database.database');
            $fieldArr = [];
            $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
            foreach ($list as $k => $v) {
                $fieldArr[] = $v['COLUMN_NAME'];
                // if ($importHeadType == 'comment') {
                //     $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
                // } else {
                //     $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
                // }
            }
            // pr($fieldArr);

            $insert = [];

            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            // $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $allRow = min($allRow, 200);
            // $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            // echo  $maxColumnNumber;

            $maxColumnNumber = 17;
            $startrow = 4;
            $fields = [];
            for ($currentRow = $startrow; $currentRow <= $startrow; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    // if($val)
                    if(!$this->auth->isSuperAdmin())
                    {
                        if($val != 'sort' || $val != 'name')
                            $val = 'tmp_'.$val;
                    }
                    $fields[] = $val;
                }
            }

    //         // if(count($fields) != $maxColumnNumber)
    //         //     $this->error(__('请上传有效的数据'));
            $msg = '';
            $errors = [];
            $addDataAll = [];
            $logDataAll = [];
            for ($currentRow = $startrow+1; $currentRow <= $allRow; $currentRow++) {
                $error = '';
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    // if(is_object($val))
                    //     echo $val->__toString();
                    $values[] = is_object($val) ? $val->__toString() : ($val == null ? '' : trim($val));
                }

                $addData = [];
                $logData = [];

                $temp = array_combine($fields, $values);
                // pr($temp);
                if($temp['name'] == '')
                {
                    $error .='项目名称必填<br>';

                }

                $res = [];
                foreach ($temp as $k => $v) {
                    // echo $k.",".$v."<br>";
                    if (in_array($k,$fieldArr) && $k !== '') {
                        $res[$k] = $v;
                    }
                }
                // pr($res);
                $row = $this->model -> where(['name'=> $temp['name']])->find();
                if($row)
                    continue;

                $addData = $this->checkfileds($res,'millionproject');
                // pr($addData);
                // $addData['pno'] = Random::uuid();
                // $addData['status'] = 100;



                if(!$this->auth->isSuperAdmin())
                {
                    $chargedep_data = $this->auth->getChargedep();

                    $chargedep_ids = $chargedep_data?$chargedep_data->chargedep_id:0;
                    // echo $chargedep_ids.",".$addData['chargedep_ids']."<br>";
                    if($chargedep_ids != $addData['street_id'])
                        $error .= '提报部门与所属街道不匹配';

                    $addData['status'] = 100;
                }
                else
                    $addData['status'] = 0;




                if($error =='')
                {
                    $addDataAll[] = $addData;

                   //  $this->model->allowField(true)->insert($addData);
                    // $logData['project_pno'] = $addData['pno'];
                    // $logData['project_name'] = $addData['name'];
                    // $logData['info'] = '导入新增';
                    // $logData['operator_id'] = $this -> auth -> id;
                    // $logData['operator_nickname'] = $this -> auth -> nickname;
                    // $logData['operate_status'] = 0;
                    // $logData['table_name'] = $this->tablename;
                    // $logDataAll[] = $logData;
                   // \app\admin\model\ProjectChecklog::create($logData);
                }
                else
                    $errors[] = $addData['name'].":<br>".$error;


            }
            // pr($errors);
            // pr($addDataAll);
            // if($msg)
            //     $msg .= '已存在';
            // else
            //     $msg = '所有项目导入成功';
            $errors_str = implode("<br>",$errors);
            if($errors_str)
                $this->error($errors_str);
            $results =$this->model->allowField(true)->saveAll($addDataAll);
            if($results === false)
                $this->error('数据保存错误');
            (new \app\admin\model\ProjectChecklog)->saveAll($logDataAll);
            $this->success('所有项目导入成功');
            exit();
        }
        $expurl = url('exptpl');
        $this->assign('expurl', $expurl);
        return $this->view->fetch();
    }

    public function exptpl(){
        $error_msg ='';

        $save_name = '过亿项目';
        $file_name = ROOT_PATH.'public/template/millionproject.xlsx';


        if (! file_exists ( $file_name )) {
            header('HTTP/1.1 404 NOT FOUND');
        } else {
            $filesize = filesize($file_name);
            header("Content-type: application/vnd.ms-excel");
            header("Content-Type: application/force-download");
            header('Content-Disposition: attachment;filename="'.$save_name.'.xlsx"');
            header( "Content-Length:   ".$filesize);
            $data = file_get_contents($file_name);
            echo $data;
        }
    }

    public function checkfileds($params,$table_name) {
        // pr($params);
        // pr($this->fiveindustryArr);
        $fields_list = Db::name('fields')->where('table_name',$table_name)->select();

        // $data = [];
        foreach ($fields_list as $key => $value) {

            if($this->auth->isSuperAdmin())
                $field = $value['item_id'];
            else
                $field = 'tmp_'.$value['item_id'];

            if(!isset($params[$field]) )
                continue;

            if($params[$field] == '')
            {
                unset($params[$field]);
                continue;
                // $params[$field] = null;
            }


            if($value['item_type'] == "select")
            {
                $params[$field] = preg_replace('/[^\x{4e00}-\x{9fa5}a-zA-Z0-9]/u',",",$params[$field]);
                $rule = json_decode($value['item_rule'], true);
                $name_field = str_replace('id','name', $field);
                $name_field_value = $params[$field];

                // echo $params[$field];
                $name_value = explode(",",$params[$field]);
                if(is_string($rule['datasource'])){
                    $tb_name = $rule['datasource'];
                    $params[$field] =  getSelectId($tb_name,$name_value);
                }else
                    $params[$field] = array_search($params[$field], $rule['datasource']);

                if(!$params[$field])
                {
                    unset($params[$field]);
                    continue;
                }

                $params[$name_field] = $name_field_value;
            }

            if($value['item_type'] == "price")
            {
                if($params[$field] == PENDING_TEXT)
                    $params[$field] = PENDING;
                if($params[$field] == ZERO )
                {
                    unset($params[$field]);
                    continue;
                }
            }
            if($value['item_type'] == "datetime" || $value['item_type'] == "date")
            {
                // var_dump($params[$field]);
                $params[$field.'_desc'] = $params[$field];
                if($params[$field] == PENDING_TEXT)
                    $params[$field] = PENDING;
                else
                    $params[$field] = dateFormatter($params[$field]);
            }

            if($value['item_type'] == 'radio')
            {
                if($params[$field] == '是')
                    $params[$field] = '1';
                elseif($params[$field] == '否')
                    $params[$field] = '1';
                else{
                    unset($params[$field]);
                    continue;
                }

            }

        }

        return $params;

    }
}
